package com.REPDPMSystem.Controller;

import com.REPDPMSystem.Service.FileService;
import com.REPDPMSystem.Service.FolderService;
import com.REPDPMSystem.Utils.R;
import com.REPDPMSystem.Entity.Folder;
import com.alibaba.fastjson2.JSONArray;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@CrossOrigin
public class FolderController {
    @Autowired
    FileService fileService;
    @Autowired
    FolderService folderService;

    @CrossOrigin
    @GetMapping("/GET/ProjectRootFolder")
    public R getProjectRootFolder(@RequestParam(value = "project_id") String project_id){
        return R.ok().data("ProjectRootFolder",new JSONArray(folderService.getRootFolderByProjectId(project_id)));
    }
    @CrossOrigin
    @GetMapping("/GET/FolderByParentFolder")
    public R getFolderByParentFolder(@RequestParam(value = "parent_id") String parent_id){
        return R.ok().data("FolderList",new JSONArray(folderService.getFolderByParentFolderId(parent_id)));
    }
    //TODO:插入时看该层级是否有同名文件夹
    //OK
    @CrossOrigin
    @PostMapping("/POST/CreateNewFolder")
    public R createNewFolder(@RequestBody Folder folder){
       return folderService.createNewFolder(folder)>0 ? R.ok() : R.error().message("新建文件夹失败！");
    }
    //OK
    @CrossOrigin
    @PostMapping("/POST/DeleteFolderByFolderId")
    public R deleteFolderByFolderId(@RequestParam(value = "folder_id") String folder_id){
        return deleteFolder(folder_id)? R.ok() : R.error().message("删除文件夹失败！");
    }

    private boolean deleteFolder(String folderId){
        List<Folder> flist=folderService.getFolderByParentFolderId(folderId);
        //不为空
        if(!flist.isEmpty()){
            for(Folder i:flist){
                deleteFolder(i.getFolder_id());
            }

        }
        //先删文件夹中的文件，再删该文件夹

        return fileService.deleteFileByFolderId(folderId) && folderService.deleteFolderByFolderId(folderId);
    }





}
